package com.demo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.ResponseResult;
import com.demo.domain.entity.LoginUser;
import com.demo.domain.entity.LogisticsLogin;
import com.demo.enums.AppHttpCodeEnum;
import com.demo.exception.SystemException;
import com.demo.mapper.LogisticsLoginMapper;
import com.demo.service.LogisticsLoginService;
import com.demo.util.JwtUtil;
import com.demo.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;


/**
*
*/
@Service
public class LogisticsLoginServiceImpl extends ServiceImpl<LogisticsLoginMapper, LogisticsLogin>
implements LogisticsLoginService{
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(LogisticsLogin logisticsLogin) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(logisticsLogin.getAccount(),logisticsLogin.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //获取userid 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        if (!Objects.equals(loginUser.getLogisticsLogin().getUserType(), logisticsLogin.getUserType())){
            return ResponseResult.errorResult(203,"用户类型选择错误");
        }
        String userId = loginUser.getLogisticsLogin().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        System.out.println();
        //把用户信息存入redis
        redisCache.setCacheObject("bloglogin:"+userId,loginUser);

        return ResponseResult.okResult(jwt);
    }

    @Override
    public ResponseResult register(LogisticsLogin logisticsLogin) {

        //对数据进行非空判断
        if(!StringUtils.hasText(logisticsLogin.getAccount())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(logisticsLogin.getPassword())) {
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        //对数据进行是否存在的判断
        if(userNameExist(logisticsLogin.getAccount())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(logisticsLogin.getPassword());
        logisticsLogin.setPassword(encodePassword);

        try {
            Date date=new Date();
            DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = dateFormat.parse(dateFormat.format(date));
            logisticsLogin.setRegistrationTime(date1);
        }catch (Exception e){
            System.out.println(e);
        }
        //存入数据库
        save(logisticsLogin);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult logout() {

            //获取token 解析获取userid
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            //获取userid
            Long userId = loginUser.getLogisticsLogin().getId();
            //删除redis中的用户信息
            redisCache.deleteObject("bloglogin:"+userId);
            return ResponseResult.okResult();
    }


    private boolean userNameExist(String userName) {
        LambdaQueryWrapper<LogisticsLogin> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(LogisticsLogin::getAccount,userName);
        return count(queryWrapper)>0;
    }
}
